%%%-------------------------------------------------------------------
%%% @author Rain
%%% @doc 数据库配置相关接口
%%% @end
%%%-------------------------------------------------------------------
-module(db_config).
-author("Rain").
-include("db.hrl").

%% API
-export([get_db_by_type/1,
    get_db_conn_args/1,
    set_config_mod/1,
    get_cfg/1
    ]).


%% @doc 设置配置模块
set_config_mod(Mod) ->
    persistent_term:put({config_mod, db}, Mod).

%% @doc 获取配置模块
get_config_mod() ->
    case persistent_term:get({config_mod, db}, undefined) of
        undefined ->
            undefined;
        Mod ->
            Mod
    end.

%% @doc 根据类型获取数据库名
get_db_by_type(DBType) ->
    PlatForm = get_cfg(platform),
    ServId = get_cfg(server_id),
    lists:concat([DBType, "_", PlatForm, "_s" ++ integer_to_list(ServId)]).


%% @doc 根据类型获取数据库进程池数量
get_db_pool_num_by_type(DBType) ->
    get_cfg(list_to_atom("db_" ++ DBType ++ "_pool")).

%% @doc 根据类型获取数据库溢出数量
get_db_pool_overflow_num_by_type(DBType) ->
    get_cfg(list_to_atom("db_" ++ DBType ++ "_pool_overflow")).

%% @doc 获取db连接参数
get_db_conn_args(DBType) ->
    DBHost = get_cfg(db_host),
    DBPort = get_cfg(db_port),
    DBUser = get_cfg(db_user),
    DBPasswd = get_cfg(db_passwd),
    DBName = get_db_by_type(DBType),
    DBPoolNum = get_db_pool_num_by_type(DBType),
    DBPoolOverflowNum = get_db_pool_overflow_num_by_type(DBType),
    SizeArgs = [{size, DBPoolNum}, {max_overflow, DBPoolOverflowNum}],
    WorkerArgs = [{host, DBHost}, {port, DBPort}, {user, DBUser},
        {password, DBPasswd}, {database, DBName}, {query_timeout, ?MYSQL_QUERY_TIMEOUT}],
    {WorkerArgs, SizeArgs}.

%% @doc 获取db配置
get_cfg(Key) ->
    ConfigMod = get_config_mod(),
    ConfigMod:get(Key).